from flask import Flask, request, jsonify
import pandas as pd

app = Flask(__name__)

# 加载模型并增加错误处理
try:
    frequent_itemsets = pd.read_pickle('./frequent_itemsets.pkl')
    rules = pd.read_pickle('./rule.pkl')
except FileNotFoundError as e:
    print(f"找不到指定的模型文件: {e}")
    exit(1)
except Exception as e:
    print(f"加载模型时发生错误: {e}")
    exit(1)

@app.route("/recommend", methods=['POST'])
def recommend():
    data = request.json.get('items', [])
    
    # 初始化推荐列表
    recommendations = []
    recommendation_scores = {}  # 记录每个推荐项目的得分
    
    # 根据关联规则生成推荐
    for idx, rule in rules.iterrows():
        antecedents = list(rule['antecedents'])
        consequents = list(rule['consequents'])
        
        # 检查规则前件是否跟输入匹配
        if set(antecedents).issubset(set(data)):
            for item in consequents:
                if item not in data:
                    # 累加推荐得分，可以根据lift或其他度量调整得分计算方式
                    recommendation_scores[item] = recommendation_scores.get(item, 0) + rule['lift']
    
    # 将推荐项目的得分转换为列表并按得分降序排列
    recommendations = sorted(recommendation_scores.items(), key=lambda x: x[1], reverse=True)
    
    # 返回推荐结果
    return jsonify({'recommendations': [item[0] for item in recommendations]})

if __name__ == "__main__":
    app.run(debug=True)  # 使用debug模式便于开发阶段调试